cmake_minimum_required(VERSION 3.5)

option(LUA_DIR "Path of Lua 5.4 source dir" OFF)
option(LUAJIT_DIR "Path of LuaJIT 2.1 source dir" OFF)
option(LUAJIT_SETUP_INCLUDE_DIR "Setup include dir if parent is present" ON)

if(CMAKE_COMPILER_IS_GNUCC)
  set(LUA_TARGET_SHARED ON)
endif()
if(DEFINED ENV{LUA_TARGET_SHARED})
  set(LUA_TARGET_SHARED $ENV{LUA_TARGET_SHARED})
endif()

get_directory_property(hasParent PARENT_DIRECTORY)
if(LUAJIT_DIR)
  project(luajit)
  include(LuaJIT.cmake)
  if (hasParent)
    set(LUA_TARGET $<TARGET_FILE:luajit> PARENT_SCOPE)
    set(LUA_LIBRARIES luajit::lib PARENT_SCOPE)
    if (LUAJIT_SETUP_INCLUDE_DIR)
      get_target_property(LUA_INCLUDE_DIR luajit::header INCLUDE_DIRECTORIES)
      set(LUA_INCLUDE_DIR ${LUA_INCLUDE_DIR} PARENT_SCOPE)
    endif()
  endif()
elseif(LUA_DIR)
  project(lua)
  include(lua.cmake)
  if (hasParent)
    set(LUA_TARGET $<TARGET_FILE:lua> PARENT_SCOPE)
    set(LUA_LIBRARIES lua::lib PARENT_SCOPE)
    if (LUAJIT_SETUP_INCLUDE_DIR)
      get_target_property(LUA_INCLUDE_DIR lua::header INCLUDE_DIRECTORIES)
      set(LUA_INCLUDE_DIR ${LUA_INCLUDE_DIR} PARENT_SCOPE)
    endif()
  endif()
  if (WITH_LIBFFI)
    include(ffi.cmake)
    set(LUA_FFI_LIBRARIES ${LUA_FFI_LIBRARIES} PARENT_SCOPE)
  endif()
else()
  message(FATAL_ERROR "Must set LUAJIT_DIR or LUA_DIR to build with CMake")
endif()
